import {
  generateGuessHbQrcode,
  getGuessHbStatus,
  setGuessHbMod,
} from '../../api/user';
import { getToken } from '../../utils/storage';

let tmpInterval = null;
Component({
  // 组件的属性列表
  properties: {
    guessHbQrcodeVisible: {
      value: false,
      type: Boolean,
      observer: function(newVal) {
        if (newVal) {
          this.initGuessHbQrcode();
        } else {
          this.endLoop();
        }
      },
    },
    splid: {
      value: '',
      type: String,
    },
    remainMoney: {
      value: '0',
      type: String,
    },
  },
  // 组件的初始数据
  data: {
    modeTypeList: [
      {
        index: 0,
        name: '模式一',
      },
      {
        index: 1,
        name: '模式二',
      },
      {
        index: 2,
        name: '模式三',
      },
    ],
    activeIndex: 0,
    currentTipText: '模式一玩法：请让新人扫码充值红包金额',
    moneyIpt: '',
    moneyIpt2: '',
    guessHbQrcodeUrl: '',
    hasGuessHbActive: false,
  },
  observers: {
    activeIndex: function(newVal) {
      let tempText = '模式一玩法：请让新人扫码充值红包金额';
      if (newVal === 1) {
        tempText = '模式二玩法：输入的竞猜金额将从红包口袋扣除';
      } else if (newVal === 2) {
        tempText = '模式三玩法：请在现场准备现金，然后发给猜中的 来宾。系统不会给猜中的来宾发送红包。';
      } else {
        tempText = '模式一玩法：请让新人扫码充值红包金额';
      }
      this.setData({
        currentTipText: tempText,
      });
    },
  },
  // 组件的方法列表
  methods: {
    initGuessHbQrcode() {
      generateGuessHbQrcode({
        liveId: this.properties.splid,
      })
        .then(res => {
           
          this.setData({
            guessHbQrcodeUrl: res.data.end_url,
          });
          this.loopGetGuessHbStatus();
        })
        .catch(err => {
            
        });
    },
    loopGetGuessHbStatus() {
      if (!tmpInterval) {
        tmpInterval = setInterval(() => {
          getGuessHbStatus({
            splid: this.properties.splid,
            token: getToken(),
          })
            .then(res => {
               
              if (res.data.chbInfo.pay_status === '200') {
                this.setData({
                  hasGuessHbActive: false,
                });
              } else {
                this.setData({
                  hasGuessHbActive: true,
                });
              }
            })
            .catch(err => {
                
            });
        }, 2000);
      }
    },
    endLoop() {
      if (tmpInterval) {
        clearInterval(tmpInterval);
        tmpInterval = null;
      }
    },
    toGuessHb() {
      if (this.data.hasGuessHbActive) {
        wx.showToast({
          title: '开启成功!打开大屏开始猜红包游戏吧!',
          icon: 'none',
        });
        wx.navigateTo({
          url:
            '/pages/index/controller/controller?liveid=' +
            this.properties.splid,
        });
      } else {
        wx.showToast({
          title: '让新人扫描这个二维码，充值开启!',
          icon: 'none',
        });
      }
    },
    saveQrcodeImg() {
      if (!this.data.guessHbQrcodeUrl) {
        wx.showToast({
          title: '二维码获取失败!',
          icon: 'none',
        });
        return;
      }
      wx.downloadFile({
        url: this.data.guessHbQrcodeUrl,
        success: function(res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: function(data) {
               
              wx.showToast({
                title: '保存成功!',
                icon: 'none',
              });
            },
          });
        },
        fail: function(err) {
            
          if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
            wx.openSetting({
              success(settingData) {
                if (settingData.authSetting['scope.writePhotosAlbum']) {
                  wx.showToast({
                    title: '获取权限成功!再次点击保存二维码',
                    icon: 'none',
                  });
                } else {
                  wx.showToast({
                    title: '获取权限失败!二维码保存失败!',
                    icon: 'none',
                  });
                }
              },
            });
          }
        },
      });
    },
    closeGuessHbRecharge() {
      this.triggerEvent('guessHbRechargeClosedEvent');
    },
    chooseModType(e) {   
      this.setData({
        activeIndex: e.currentTarget.dataset.index,
      });
      if (this.data.activeIndex === 0) {
        this.loopGetGuessHbStatus();
      } else {
        this.endLoop();
      }
    },
    handleInput(e) {
       
      this.setData({
        moneyIpt: e.detail.value,
      });
    },
    handleInput2(e) {
       
      this.setData({
        moneyIpt2: e.detail.value,
      });
    },
    validateIpt(numStr) {
      const reg = /^\d+(?=\.{0,1}\d+$|$)/;
      let flag = true;
      // 验证数字
      if (!reg.test(numStr)) {
        wx.showToast({
          title: '请输入正确的数字!',
          icon: 'none',
        });
        flag = false;
        return flag;
      }
      // 验证小数不超过两位,整数不超过4位
      if (numStr.indexOf('.') > -1) {
        if (numStr.split('.')[1].length > 2) {
          wx.showToast({
            title: '小数不能超过两位!',
            icon: 'none',
          });
          flag = false;
          return flag;
        } else if (numStr.split('.')[0].length > 4) {
          wx.showToast({
            title: '整数不能超过四位!',
            icon: 'none',
          });
          flag = false;
          return flag;
        }
      } else {
        if (numStr.length > 4) {
          wx.showToast({
            title: '整数不能超过四位!',
            icon: 'none',
          });
          flag = false;
          return flag;
        }
      }
      return flag;
    },
    // 补零
    fillZero(numStr) {
      let resultStr = numStr;
      // .2 2.
      if (numStr.indexOf('.') > -1) {
        const tempNumArr = numStr.split('.');
        if (tempNumArr[0] === '') {
          resultStr = '0.' + tempNumArr[1];
        } else if (tempNumArr[1] === '') {
          resultStr = tempNumArr[1] + '.0';
        }
      }
      return resultStr;
    },
    // 去零
    removeZero(numStr) {
      let resultNumStr = numStr;
      // 05 005 5.0 5.10
      // 050
      if (numStr.indexOf('.') === -1) {
        // 整数
        const tempArr = numStr.split('');
        const tempLen = tempArr.length;
        let tempIndex = -1;
        // 遍历数组找到第一个非0数字的位置索引
        for (let i = 0; i < tempLen; i += 1) {
          if (tempArr[i] !== '0') {
            tempIndex = i;
            break;
          }
        }
        if (tempIndex > -1) {
          // 第一个非0数字前面的0全部清空
          for (let j = 0; j < tempIndex; j += 1) {
            tempArr[j] = '';
          }
          resultNumStr = tempArr.join('');
        } else {
          resultNumStr = '0';
        }
      } else {
        // 小数
        const interStr = numStr.split('.')[0];
        const decimalStr = numStr.split('.')[1];
        const interArr = interStr.split('');
        const decimalArr = decimalStr.split('');
        // 处理整数部分
        const tempLen = interArr.length;
        let tempIndex = -1;
        // 遍历数组找到第一个非0数字的位置索引
        for (let i = 0; i < tempLen; i += 1) {
          if (interArr[i] !== '0') {
            tempIndex = i;
            break;
          }
        }
        if (tempIndex > -1) {
          // 第一个非0数字前面的0全部清空
          for (let j = 0; j < tempIndex; j += 1) {
            if (interArr[j] === 0) {
              interArr[j] = '';
            }
          }
        } else {
          interArr = ['0'];
        }

        // 处理小数 .01 .10 .0 .1 .00
        const tempLen2 = decimalArr.length;
        let tempIndex2 = -1;
        // 遍历数组找到第一个非0数字的位置索引
        for (let i = 0; i < tempLen; i += 1) {
          if (decimalArr[i] !== '0') {
            tempIndex2 = i;
            break;
          }
        }
        if (tempIndex2 > -1) {
          // 第一个非0数字后面的0全部清空
          for (let i = tempIndex2 + 1; i < tempLen2; i += 1) {
            if (decimalArr[i] === 0) {
              decimalArr[i] = '';
            }
          }
        } else {
          decimalArr = ['0'];
        }

        resultNumStr = interArr.join('') + '.' + decimalArr.join('');
      }
      return resultNumStr;
    },
    confirmMoney() {
      let tempMoneyIpt = this.data.moneyIpt;
      if (!this.validateIpt(tempMoneyIpt)) {
        return;
      }
      // 补零
      tempMoneyIpt = this.fillZero(tempMoneyIpt);
      // 去零
      tempMoneyIpt = this.removeZero(tempMoneyIpt);
      // 化整数
      tempMoneyIpt = parseFloat(tempMoneyIpt);
      this.setData({
        moneyIpt: tempMoneyIpt + '',
      });
      setGuessHbMod({
        splid: this.properties.splid,
        token: getToken(),
        type: this.data.activeIndex === 1 ? '2' : '1',
        guess_money: this.data.moneyIpt + '',
      })
        .then(res => {
           
          if (res.data.code === '200') {
            wx.showToast({
              title: '开启成功!打开大屏开始猜红包游戏吧!',
              icon: 'none',
            });
            wx.navigateTo({
              url:
                '/pages/index/controller/controller?liveid=' +
                this.properties.splid,
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
            });
          }
        })
        .catch(err => {
            
        });
    },
    confirmMoney2() {
      let tempMoneyIpt = this.data.moneyIpt2;
      if (!this.validateIpt(tempMoneyIpt)) {
        return;
      }
      // 补零
      tempMoneyIpt = this.fillZero(tempMoneyIpt);
      // 去零
      tempMoneyIpt = this.removeZero(tempMoneyIpt);
      // 化整数
      tempMoneyIpt = parseFloat(tempMoneyIpt);
      this.setData({
        moneyIpt2: tempMoneyIpt + '',
      });
      setGuessHbMod({
        splid: this.properties.splid,
        token: getToken(),
        type: this.data.activeIndex === 1 ? '2' : '1',
        guess_money: this.data.moneyIpt2,
      })
        .then(res => {
           
          if (res.data.code === '200') {
            wx.showToast({
              title: '开启成功!打开大屏开始猜红包游戏吧!',
              icon: 'none',
            });
            wx.navigateTo({
              url:
                '/pages/index/controller/controller?liveid=' +
                this.properties.splid,
            });
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
            });
          }
        })
        .catch(err => {
            
        });
    },
  },
});
